﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
using Android;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.OS;
using Android.Runtime;
using Android.Util;
using Android.Views;
using Android.Widget;
using Android.Graphics;
using Android.Text;

namespace Timer
{
	[Activity (Label = "Tiempos", Icon = "@drawable/icon", ScreenOrientation = ScreenOrientation.Portrait)]			
	public class MainActivity_2 : Activity
	{
		System.Threading.Timer timer1;
		System.Threading.Timer timer2;
		System.Threading.Timer timer3;
		System.Threading.Timer timer4;
		System.Threading.Timer timer5;
		DateTime StartTime1;
		DateTime StartTime2;
		DateTime StartTime3;
		DateTime StartTime4;
		DateTime StartTime5;

		string bWifi = "true";
		string bWSSync = "true";
		string IdUsuario = "";
		string Clave_de_Acceso = "";
		string Contrasena = "";
		string cURL = "";
		bool verTiempos = false;
		bool bTimer1 = false, bTimer2 = false, bTimer3 = false, bTimer4 = false, bTimer5 = false;
		DataManager sqldb;

		protected override void OnCreate (Bundle bundle)
		{
			base.OnCreate (bundle);

			IdUsuario = Intent.GetStringExtra ("IdUsuario") ?? "Data not available";
			Clave_de_Acceso = Intent.GetStringExtra ("Clave_de_Acceso") ?? "Data not available";
			Contrasena = Intent.GetStringExtra ("Contrasena") ?? "Data not available";
			bWifi = Intent.GetStringExtra ("bWifi") ?? "true";
			bWSSync = Intent.GetStringExtra ("bWSSync") ?? "true";
			cURL = Intent.GetStringExtra ("cURL") ?? "http://www.totalcase.com.mx/webservicessismop/Registro_de_Tiempos_de_Proceso2WS.asmx";
			verTiempos = false;
			// Create your application here
			SetContentView (Resource.Layout.Main_2);
			Button btnTiempos = FindViewById<Button> (Resource.Id.btnTiempos);
			Button btnGrabar = FindViewById<Button> (Resource.Id.btnGrabar);
			Button btnEnviar = FindViewById<Button> (Resource.Id.btnEnviar);
			Button btnTimer1 = FindViewById<Button> (Resource.Id.btnTimer1);
			Button btnTimer2 = FindViewById<Button> (Resource.Id.btnTimer2);
			Button btnTimer3 = FindViewById<Button> (Resource.Id.btnTimer3);
			Button btnTimer4 = FindViewById<Button> (Resource.Id.btnTimer4);
			Button btnTimer5 = FindViewById<Button> (Resource.Id.btnTimer5);
			btnTiempos.Click += (object sender, EventArgs e) => { VerTiempos(sender, e); };
			btnGrabar.Click += (object sender, EventArgs e) => { Grabar(sender, e); };
			btnEnviar.Click += (object sender, EventArgs e) => { Enviar(sender, e); };
			btnTimer1.Click += (object sender, EventArgs e) => { StartTimer1(sender, e); };
			btnTimer2.Click += (object sender, EventArgs e) => { StartTimer2(sender, e); };
			btnTimer3.Click += (object sender, EventArgs e) => { StartTimer3(sender, e); };
			btnTimer4.Click += (object sender, EventArgs e) => { StartTimer4(sender, e); };
			btnTimer5.Click += (object sender, EventArgs e) => { StartTimer5(sender, e); };
			btnGrabar.Enabled = false;
		}

		private void Enviar(object sender, EventArgs e)
		{
			try
			{
				bool inserted = false;
				var cm = (ConnectivityManager)GetSystemService(ConnectivityService);

				var mobileState = cm.GetNetworkInfo(ConnectivityType.Wifi).GetState();
				if (mobileState == NetworkInfo.State.Connected || bWifi == "false")
				{
					var ws = new Registro_WS.Registro_de_Tiempos_de_Proceso2WS(cURL);

					sqldb = new DataManager ();
					sqldb.OpenDatabase2("timer_db.db3");
					List<Registro_de_Tiempos_de_Proceso> registros = sqldb.GetTiempos ();
					sqldb.CloseDatabase2 ();

					foreach (var r in registros) {
						inserted = true;
						if (bWSSync == "false")
							ws.BeginInsert(Clave_de_Acceso, Contrasena, r.Fecha, r.Hora, r.Usuario, r.Proceso, r.Tiempo_1, r.Tiempo_2, r.Tiempo_3, r.Tiempo_4, r.Tiempo_5, r.Promedio, true, WS_CallBack, ws);
						else
							ws.Insert (Clave_de_Acceso, Contrasena, r.Fecha, r.Hora, r.Usuario, r.Proceso, r.Tiempo_1, r.Tiempo_2, r.Tiempo_3, r.Tiempo_4, r.Tiempo_5, r.Promedio, true);
						r.Enviado = 1;
						sqldb.OpenDatabase2("timer_db.db3");
						sqldb.UpdateRegistro(r);
						sqldb.CloseDatabase2();
					}

					if (inserted)
						Messagebox ("Aviso", "Los registros de tiempos han sido enviados");
					else
						Messagebox ("Aviso", "No posee registros pendientes de envío");
				}
				else
				{
					Messagebox ("Error", "No posee una conexión WIFI activa");
					return;
				}
			}
			catch (Exception ex)
			{
				Log.Error ("Timer", ex.Message);
				Log.Error ("Timer", ex.StackTrace);
				if (ex.InnerException != null) Log.Error ("Timer", ex.InnerException.ToString());
				if (ex.Source != null) Log.Error ("Timer", ex.Source);
				Messagebox ("Error", String.Format("Ocurrió un error:{0}", ex.Message));
				return;
			}
		}

		void WS_CallBack (IAsyncResult ar)
		{
			var ws = ar.AsyncState as Registro_WS.Registro_de_Tiempos_de_Proceso2WS;
			ws.EndInsert(ar);
		}

		private void Grabar(object sender, EventArgs e)
		{
			TextView chr1 = FindViewById<TextView> (Resource.Id.crono1);
			TextView chr2 = FindViewById<TextView> (Resource.Id.crono2);
			TextView chr3 = FindViewById<TextView> (Resource.Id.crono3);
			TextView chr4 = FindViewById<TextView> (Resource.Id.crono4);
			TextView chr5 = FindViewById<TextView> (Resource.Id.crono5);
			TextView txtAvg = FindViewById<TextView> (Resource.Id.txtAVG);
			EditText txtProcesoNro = FindViewById<EditText> (Resource.Id.txtProcesoNro);
			Button btnTiempos = FindViewById<Button> (Resource.Id.btnTiempos);
			Button btnGrabar = FindViewById<Button> (Resource.Id.btnGrabar);

			//valido que todos los timers esten apagados
			if (bTimer1 || bTimer2 || bTimer3 || bTimer4 || bTimer5) {
				Messagebox ("Error", "Para guardar, todos los timers deben estar detenidos");
				return;
			}

			btnTiempos.Visibility = ViewStates.Invisible;

			Registro_de_Tiempos_de_Proceso registro = new Registro_de_Tiempos_de_Proceso ();
			registro.Fecha = DateTime.Now;
			registro.Hora = DateTime.Now.ToString("HH:mm:ss");
			registro.Usuario = Convert.ToInt16(IdUsuario);
			registro.Proceso = txtProcesoNro.Text;
			registro.Tiempo_1 = chr1.Text;
			registro.Tiempo_2 = chr2.Text;
			registro.Tiempo_3 = chr3.Text;
			registro.Tiempo_4 = chr4.Text;
			registro.Tiempo_5 = chr5.Text;
			registro.Promedio = txtAvg.Text;
			registro.Enviado = 0;

			sqldb = new DataManager ();
			sqldb.OpenDatabase2("timer_db.db3");
			if (sqldb.InsertTiempo (registro) == -1) {
				Messagebox ("Error", "Ocurrió un error guardando los tiempos");
			} else {
				chr1.Text = "00:00:000";
				chr2.Text = "00:00:000";
				chr3.Text = "00:00:000";
				chr4.Text = "00:00:000";
				chr5.Text = "00:00:000";
				txtAvg.Text = "00:00:000";
				btnGrabar.Enabled = false;
			}
			sqldb.CloseDatabase2 ();
		}

		private void VerTiempos(object sender, EventArgs e)
		{
			if (!verTiempos) {
				EditText txtProcesoNro = FindViewById<EditText> (Resource.Id.txtProcesoNro);
				Button btnAVG = FindViewById<Button> (Resource.Id.btnAVG);
				TextView txtProcesoDesc = FindViewById<TextView> (Resource.Id.txtProcesoDesc);
				TextView txtAvg = FindViewById<TextView> (Resource.Id.txtAVG);
				TextView chr1 = FindViewById<TextView> (Resource.Id.crono1);
				TextView chr2 = FindViewById<TextView> (Resource.Id.crono2);
				TextView chr3 = FindViewById<TextView> (Resource.Id.crono3);
				TextView chr4 = FindViewById<TextView> (Resource.Id.crono4);
				TextView chr5 = FindViewById<TextView> (Resource.Id.crono5);
				Button btnEnviar = FindViewById<Button> (Resource.Id.btnEnviar);
				Button btnGrabar = FindViewById<Button> (Resource.Id.btnGrabar);
				Button btnTiempos = FindViewById<Button> (Resource.Id.btnTiempos);
				Button btnTimer1 = FindViewById<Button> (Resource.Id.btnTimer1);
				Button btnTimer2 = FindViewById<Button> (Resource.Id.btnTimer2);
				Button btnTimer3 = FindViewById<Button> (Resource.Id.btnTimer3);
				Button btnTimer4 = FindViewById<Button> (Resource.Id.btnTimer4);
				Button btnTimer5 = FindViewById<Button> (Resource.Id.btnTimer5);
				TableLayout tblLayout = FindViewById<TableLayout> (Resource.Id.tableLayout3);

				sqldb = new DataManager ();
				sqldb.OpenDatabase2 ("timer_db.db3");
				txtProcesoDesc.Text = sqldb.GetProceso (txtProcesoNro.Text);
				sqldb.CloseDatabase2 ();

				if (txtProcesoDesc.Text.Length == 0) {
					tblLayout.Visibility = ViewStates.Invisible;
					txtProcesoDesc.Visibility = ViewStates.Invisible;
					btnAVG.Visibility = ViewStates.Invisible;
					txtAvg.Visibility = ViewStates.Invisible;
					btnTimer1.Visibility = ViewStates.Invisible;
					btnTimer2.Visibility = ViewStates.Invisible;
					btnTimer3.Visibility = ViewStates.Invisible;
					btnTimer4.Visibility = ViewStates.Invisible;
					btnTimer5.Visibility = ViewStates.Invisible;
					btnGrabar.Visibility = ViewStates.Invisible;
					btnEnviar.Visibility = ViewStates.Visible;
					chr1.Visibility = ViewStates.Invisible;
					chr2.Visibility = ViewStates.Invisible;
					chr3.Visibility = ViewStates.Invisible;
					chr4.Visibility = ViewStates.Invisible;
					chr5.Visibility = ViewStates.Invisible;

					Messagebox ("Error", "No existe el proceso");
				} else {
					txtProcesoNro.Enabled = false;
					tblLayout.Visibility = ViewStates.Visible;
					txtProcesoDesc.Visibility = ViewStates.Visible;
					btnAVG.Visibility = ViewStates.Visible;
					txtAvg.Visibility = ViewStates.Visible;
					btnTimer1.Visibility = ViewStates.Visible;
					btnTimer2.Visibility = ViewStates.Visible;
					btnTimer3.Visibility = ViewStates.Visible;
					btnTimer4.Visibility = ViewStates.Visible;
					btnTimer5.Visibility = ViewStates.Visible;
					btnGrabar.Visibility = ViewStates.Visible;
					btnEnviar.Visibility = ViewStates.Invisible;
					btnTiempos.Visibility = ViewStates.Invisible;
					chr1.Visibility = ViewStates.Visible;
					chr2.Visibility = ViewStates.Visible;
					chr3.Visibility = ViewStates.Visible;
					chr4.Visibility = ViewStates.Visible;
					chr5.Visibility = ViewStates.Visible;

					verTiempos = true;
				}
			}
		}

		private void StartTimer1(object sender, EventArgs e)
		{
			StartTimers (ref bTimer1, ref timer1, ref StartTime1);

			Button btnTimer1 = FindViewById<Button> (Resource.Id.btnTimer1);
			TextView chr1 = FindViewById<TextView> (Resource.Id.crono1);
			if (!bTimer1)
				btnTimer1.SetBackgroundResource (Resource.Drawable.buttonStopped);
			else {
				chr1.SetTextColor(Color.DimGray);
				btnTimer1.SetBackgroundResource (Resource.Drawable.buttonRunning);
			}
		}

		private void StartTimer2(object sender, EventArgs e)
		{
			StartTimers (ref bTimer2, ref timer2, ref StartTime2);

			Button btnTimer2 = FindViewById<Button> (Resource.Id.btnTimer2);
			TextView chr2 = FindViewById<TextView> (Resource.Id.crono2);
			if (!bTimer2)
				btnTimer2.SetBackgroundResource (Resource.Drawable.buttonStopped);
			else {
				chr2.SetTextColor(Color.DimGray);
				btnTimer2.SetBackgroundResource (Resource.Drawable.buttonRunning);
			}
		}

		private void StartTimer3(object sender, EventArgs e)
		{
			StartTimers (ref bTimer3, ref timer3, ref StartTime3);

			Button btnTimer3 = FindViewById<Button> (Resource.Id.btnTimer3);
			TextView chr3 = FindViewById<TextView> (Resource.Id.crono3);
			if (!bTimer3)
				btnTimer3.SetBackgroundResource (Resource.Drawable.buttonStopped);
			else {
				chr3.SetTextColor (Color.DimGray);
				btnTimer3.SetBackgroundResource (Resource.Drawable.buttonRunning);
			}
		}

		private void StartTimer4(object sender, EventArgs e)
		{
			StartTimers (ref bTimer4, ref timer4, ref StartTime4);

			Button btnTimer4 = FindViewById<Button> (Resource.Id.btnTimer4);
			TextView chr4 = FindViewById<TextView> (Resource.Id.crono4);
			if (!bTimer4)
				btnTimer4.SetBackgroundResource (Resource.Drawable.buttonStopped);
			else {
				chr4.SetTextColor (Color.DimGray);
				btnTimer4.SetBackgroundResource (Resource.Drawable.buttonRunning);
			}
		}

		private void StartTimer5(object sender, EventArgs e)
		{
			Button btnTimer5 = FindViewById<Button> (Resource.Id.btnTimer5);
			TextView chr5b = FindViewById<TextView> (Resource.Id.crono5);

			StartTimers (ref bTimer5, ref timer5, ref StartTime5);
			if (!bTimer5) {
				TextView chr1 = FindViewById<TextView> (Resource.Id.crono1);
				TextView chr2 = FindViewById<TextView> (Resource.Id.crono2);
				TextView chr3 = FindViewById<TextView> (Resource.Id.crono3);
				TextView chr4 = FindViewById<TextView> (Resource.Id.crono4);
				TextView chr5 = FindViewById<TextView> (Resource.Id.crono5);
				TextView txtAvg = FindViewById<TextView> (Resource.Id.txtAVG);

				char[] delimiterChar = { ':' };

				TimeSpan t1 = new TimeSpan(0,0,Convert.ToInt16(chr1.Text.Split(delimiterChar)[0]),Convert.ToInt16(chr1.Text.Split(delimiterChar)[1]),Convert.ToInt16(chr1.Text.Split(delimiterChar)[2]));
				TimeSpan t2 = new TimeSpan(0,0,Convert.ToInt16(chr2.Text.Split(delimiterChar)[0]),Convert.ToInt16(chr2.Text.Split(delimiterChar)[1]),Convert.ToInt16(chr2.Text.Split(delimiterChar)[2]));
				TimeSpan t3 = new TimeSpan(0,0,Convert.ToInt16(chr3.Text.Split(delimiterChar)[0]),Convert.ToInt16(chr3.Text.Split(delimiterChar)[1]),Convert.ToInt16(chr3.Text.Split(delimiterChar)[2]));
				TimeSpan t4 = new TimeSpan(0,0,Convert.ToInt16(chr4.Text.Split(delimiterChar)[0]),Convert.ToInt16(chr4.Text.Split(delimiterChar)[1]),Convert.ToInt16(chr4.Text.Split(delimiterChar)[2]));
				TimeSpan t5 = new TimeSpan(0,0,Convert.ToInt16(chr5.Text.Split(delimiterChar)[0]),Convert.ToInt16(chr5.Text.Split(delimiterChar)[1]),Convert.ToInt16(chr5.Text.Split(delimiterChar)[2]));
				Button btnGrabar = FindViewById<Button> (Resource.Id.btnGrabar);
				txtAvg.Text = TimeSpan.FromTicks ((t1 + t2 + t3 + t4 + t5).Ticks / 5).ToString (@"mm\:ss\:fff");
				btnGrabar.Enabled = true;
				btnTimer5.SetBackgroundResource (Resource.Drawable.buttonStopped);
			}
			else {
				chr5b.SetTextColor(Color.DimGray);
				btnTimer5.SetBackgroundResource (Resource.Drawable.buttonRunning);
			}
		}

		void Timer_Tick(object sender)
		{
			TextView chr1 = FindViewById<TextView> (Resource.Id.crono1);
			TextView chr2 = FindViewById<TextView> (Resource.Id.crono2);
			TextView chr3 = FindViewById<TextView> (Resource.Id.crono3);
			TextView chr4 = FindViewById<TextView> (Resource.Id.crono4);
			TextView chr5 = FindViewById<TextView> (Resource.Id.crono5);

			if (bTimer1) {
				TimeSpan t = DateTime.Now - StartTime1;
				RunOnUiThread (() => chr1.Text = String.Format ("{0}:{1}:{2}", t.Minutes.ToString ("00"), t.Seconds.ToString ("00"), t.Milliseconds.ToString ("000")));
			}
			if (bTimer2) {
				TimeSpan t = DateTime.Now - StartTime2;
				RunOnUiThread (() => chr2.Text = String.Format ("{0}:{1}:{2}", t.Minutes.ToString ("00"), t.Seconds.ToString ("00"), t.Milliseconds.ToString ("000")));
			}
			if (bTimer3) {
				TimeSpan t = DateTime.Now - StartTime3;
				RunOnUiThread (() => chr3.Text = String.Format ("{0}:{1}:{2}", t.Minutes.ToString ("00"), t.Seconds.ToString ("00"), t.Milliseconds.ToString ("000")));
			}
			if (bTimer4) {
				TimeSpan t = DateTime.Now - StartTime4;
				RunOnUiThread (() => chr4.Text = String.Format ("{0}:{1}:{2}", t.Minutes.ToString ("00"), t.Seconds.ToString ("00"), t.Milliseconds.ToString ("000")));
			}
			if (bTimer5) {
				TimeSpan t = DateTime.Now - StartTime5;
				RunOnUiThread (() => chr5.Text = String.Format ("{0}:{1}:{2}", t.Minutes.ToString ("00"), t.Seconds.ToString ("00"), t.Milliseconds.ToString ("000")));
			}
		}

		private void StartTimers(ref bool timerStatus, ref System.Threading.Timer timer, ref DateTime inicio)
		{
			if (!timerStatus) {
				timerStatus = true;
				inicio = DateTime.Now;
				timer = new System.Threading.Timer (Timer_Tick, null, TimeSpan.Zero, TimeSpan.FromMilliseconds (50));
			}
			else {
				timerStatus = false;
				timer.Dispose ();
				timer = null;
			} 
		}

		private void Messagebox(string titulo, string mensaje)
		{
			AlertDialog.Builder builder = new AlertDialog.Builder (this);
			AlertDialog alertDialog = builder.Create ();
			alertDialog.SetTitle (titulo);
			alertDialog.SetIcon (Android.Resource.Drawable.IcDialogAlert);
			alertDialog.SetMessage (mensaje);
			alertDialog.SetButton ("OK", (s, ev) => {
			});
			alertDialog.Show ();
		}
	}
}

